import os
from starlette.exceptions import HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi import status
from .log import getLogger

logger=getLogger(os.environ.get('APP_NAME'))


async def global_http_exception_handler(request,exc):
    """全局HTTP异常处理函数"""
    print(exc,type(exc),dir(exc))
    if exc.status_code==500:
        err_msg='Server Internal Error'
    else:
        err_msg=exc.detail
    logger.error(err_msg)
    return JSONResponse({
        'code':exc.status_code,
        'err_msg':err_msg,
        'status':'Failed'
    })

async def global_validation_exception_handler(request,exc):
    """全局校验异常处理函数"""
    return JSONResponse({
        'code':status.HTTP_422_UNPROCESSABLE_ENTITY,
        'err_msg':exc.errors()[0],
        'status':'Failed'
    })

